import { Msg, MsgLoading, MsgLoadingClear } from '@C/Msg'
import setCV from '@U/setCV'
import type { IObj } from '@/interface'

export default async (url: string, open = true, copy = true, isDocument = false) => {
    await MsgLoading()
    uni.downloadFile({
        url: /^http/.test(url) ? url : `https://img2.shoudaozi.com/${url}`,
        success(data) {
            if (data.statusCode === 200) {
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                // @ts-ignore
                wx.getFileSystemManager().saveFile({
                    tempFilePath: data.tempFilePath,
                    success(saveRes: IObj) {
                        MsgLoadingClear()
                        Msg({ icon: 'success', msg: '下载成功' })

                        if (copy) {
                            setCV(saveRes.savedFilePath)
                        }
                        if (open) {
                            setTimeout(() => Msg({ msg: '路径已复制，即将自动打开' }), 500)
                            setTimeout(() => {
                                uni.openDocument({ filePath: saveRes.savedFilePath })
                                if (!isDocument) {
                                    uni.previewImage({
                                        urls: [saveRes.savedFilePath],
                                    })
                                }
                            }, 2000)
                        }
                    },
                    fail() { MsgLoadingClear({ icon: 'error', msg: '下载失败' }) },
                })
            } else MsgLoadingClear({ icon: 'error', msg: '下载失败' })
        },
        fail() { MsgLoadingClear({ icon: 'error', msg: '下载失败' }) },
    })

    // #ifdef H5
    window.location.href = /^http/.test(url) ? url : `https://img2.shoudaozi.com/${url}`
    // #endif
}
